<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/crypto-js@4.1.1/crypto-js.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <input type="file" name="" id="uploader">
    <progress id='progress' value="0"></progress>
    <p id='output'></p>


</body>
<script>
    const uploader = document.getElementById('uploader')
    const output = document.getElementById('output')
    const progress = document.getElementById('progress')
    uploader.addEventListener('change', async (event) => {
        const { files } = event.target
        const [file] = files//取第一个
        console.log(file)
        if (!file) {
            return
        }
        uploaded.value=null
        const content = await read(file)
        const hash = CryptoJS.MD5(content)
        const { size, name, type } = file
        progress.max = size
        const chunkSize = 64 * 1024 //64K
        const breakPoint = 1024 * 1024
        let uploaded = 0 //已经上传了多少
        let local = localStorage.getItem(hash)//断点续传
        console.log(local, 1212121, Boolean(null))
        if (local) {
            uploaded = Number(local)
        }
        console.log(uploaded, size, hash)
        while (uploaded < size) {
            console.log(uploaded, uploaded + chunkSize, type)
            const chunk = file.slice(uploaded, uploaded + chunkSize, type)
            console.log(chunk)
            const formData = new FormData()
            formData.append('name', name)
            formData.append('type', type)
            formData.append('file', chunk)
            formData.append('hash', hash)
            formData.append('offset', uploaded)
            formData.append('size', size)
            try {
                await axios.post('http://localhost:3000/api/upload', formData)
            } catch (error) {
                output.innerHTML = '上传失败' + error.message
                return
            }
            uploaded += chunk.size
            localStorage.setItem(hash, uploaded)
            progress.value = uploaded
            //    if(uploaded>breakPoint){
            //        return
            //    }
        }
        output.innerHTML = '上传成功'
    })


    async function read(file) {
        const reader = new FileReader();
        return new Promise((resolve, reject) => {
            reader.onload = function () {
                resolve(reader.result)
            }
            reader.onerror = reject
            reader.readAsBinaryString(file)
        })

    }
</script>

</html>